import React from 'react';
import { Link, Switch, Route, Redirect, useLocation, useHistory } from 'react-router-dom';

function PublicPage () {
    return <h3>Public</h3>;
}

function ProtectedPage () {
    return <h3>Protected</h3>;
}

const fakeAuth = {
    isAuthenticated: false,
    signin (cb) {
        fakeAuth.isAuthenticated = true;
        setTimeout(cb, 100); // fake async
    },
    signout (cb) {
        fakeAuth.isAuthenticated = false;
        setTimeout(cb, 100);
    }
};

function AuthButton () {
    let history = useHistory();

    return fakeAuth.isAuthenticated ? (
        <p>
            Welcome!{' '}
            <button onClick={() => {
                fakeAuth.signout(() => history.push('/'));
            }}>
                Sign out
            </button>
        </p>
    ) : (
        <p>You are not logged in.</p>
    );
}

const LoginPage = (props) => {
    let { state: { from } } = useLocation();
    let { replace } = useHistory();

    const login = () => {
        fakeAuth.signin(() => {
            replace(from);
        });
    };

    return (
        <div>
            <p>You must log in to view the page at {from}</p>
            <button onClick={login}>Log in</button>
        </div>
    );
};

const PrivateRoute = ({ children, ...rest }) => {
    let { pathname } = useLocation();
    return (
        <Route {...rest}>
            {
                fakeAuth.isAuthenticated ? children : <Redirect from={pathname} to={{
                    pathname: '/login',
                    state: { from: pathname }
                }}></Redirect>
            }
        </Route>
    );
};

class App extends React.Component {
    render () {
        return (
            <div>
                <AuthButton />
                <ul>
                    <li>
                        <Link to="/public">Public Page</Link>
                    </li>
                    <li>
                        <Link to="/protected">Protected Page</Link>
                    </li>
                </ul>
                <Switch>
                    <Route exact path="/public">
                        <PublicPage />
                    </Route>
                    <PrivateRoute path="/protected">
                        <ProtectedPage />
                    </PrivateRoute>
                    <Route exact path="/login">
                        <LoginPage />
                    </Route>
                    <Redirect exact from="/" to="/public"></Redirect>
                </Switch>
            </div>
        );
    }
}

export default App;
